package com.example.ttt.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import ws.schild.jave.Encoder;
import ws.schild.jave.EncoderException;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.encode.AudioAttributes;
import ws.schild.jave.encode.EncodingAttributes;

import java.io.File;
import java.util.Objects;

/*
 * 音频格式转换demo
 * */

@Slf4j
@Component
public class AudioTransfer {

    // test demo
    public static void main(String[] args) {
        AudioTransfer audioTransfer = new AudioTransfer();
        audioTransfer.startToWav("","");
    }

    /*
    * 将音频转换为wav格式
    * */
    public void startToWav(String sourcePath, String targetPath) {

        if (Objects.isNull(sourcePath) || Objects.isNull(targetPath)){
            log.info("文件地址异常：{} && {}",sourcePath,targetPath);
            throw new RuntimeException("文件地址异常");
        }

        try {

            // file
            File source = new File(sourcePath);
            File target = new File(targetPath);

            // Audio Attributes
            AudioAttributes audio = new AudioAttributes();
            audio.setCodec("libmp3lame");
            audio.setBitRate(128000);
            audio.setChannels(2);
            audio.setSamplingRate(44100);

            // Encoding attributes
            EncodingAttributes attrs = new EncodingAttributes();
            attrs.setOutputFormat("wav");
            attrs.setAudioAttributes(audio);

            // Encode
            Encoder encoder = new Encoder();
            encoder.encode(new MultimediaObject(source), target, attrs);
        } catch (EncoderException e) {
            log.info("文件转换失败：{}",sourcePath);
            throw new RuntimeException(e);
        }
    }
}
